{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "# 7 层级索引（hierarchical indexing）"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cloth  size\n",
      "a      0       0.496714\n",
      "       1      -0.138264\n",
      "       2       0.647689\n",
      "b      0       1.523030\n",
      "       1      -0.234153\n",
      "       2      -0.234137\n",
      "c      0       1.579213\n",
      "       1       0.767435\n",
      "       2      -0.469474\n",
      "d      0       0.542560\n",
      "       1      -0.463418\n",
      "       2      -0.465730\n",
      "dtype: float64\n",
      "--------------------------------------------------\n",
      "MultiIndex([('a', 0),\n",
      "            ('a', 1),\n",
      "            ('a', 2),\n",
      "            ('b', 0),\n",
      "            ('b', 1),\n",
      "            ('b', 2),\n",
      "            ('c', 0),\n",
      "            ('c', 1),\n",
      "            ('c', 2),\n",
      "            ('d', 0),\n",
      "            ('d', 1),\n",
      "            ('d', 2)],\n",
      "           names=['cloth', 'size'])\n",
      "--------------------------------------------------\n",
      "<class 'pandas.core.indexes.multi.MultiIndex'>\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "np.random.seed(42)\n",
    "\n",
    "#MultiIndex是层级索引，索引类型的一种\n",
    "index1 = pd.MultiIndex.from_arrays([['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd'],\n",
    "                [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]], names=['cloth', 'size'])\n",
    "\n",
    "ser_obj = pd.Series(np.random.randn(12),index=index1)\n",
    "print(ser_obj)\n",
    "print('-'*50)\n",
    "\n",
    "print(ser_obj.index)\n",
    "print('-'*50)\n",
    "\n",
    "print(type(ser_obj.index)) #索引类型，MultiIndex\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2024-05-03T05:10:43.995073500Z",
     "start_time": "2024-05-03T05:10:43.968958Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[['a', 'b', 'c', 'd'], [0, 1, 2]]\n",
      "[[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]]\n"
     ]
    }
   ],
   "source": [
    "print(ser_obj.index.levels) #层级索引的索引值\n",
    "print(ser_obj.index.codes)  #没那么重要，代表索引的位置"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-05-03T05:09:57.408561Z",
     "start_time": "2024-05-03T05:09:57.369665100Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "size\n",
      "0    1.579213\n",
      "1    0.767435\n",
      "2   -0.469474\n",
      "dtype: float64\n",
      "--------------------------------------------------\n",
      "0.6476885381006925\n",
      "--------------------------------------------------\n",
      "cloth\n",
      "a    0.647689\n",
      "b   -0.234137\n",
      "c   -0.469474\n",
      "d   -0.465730\n",
      "dtype: float64\n"
     ]
    }
   ],
   "source": [
    "# series的层级索引如何取数据\n",
    "print(ser_obj['c']) #取出c的所有数据，取出的是series\n",
    "print('-'*50)\n",
    "\n",
    "print(ser_obj['a', 2])\n",
    "print('-'*50)\n",
    "\n",
    "print(ser_obj[:, 2]) #取出所有行的内层索引为2的数据"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2024-05-03T05:13:49.136895500Z",
     "start_time": "2024-05-03T05:13:49.123931800Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## swaplevel交换层级"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cloth  size\n",
      "a      0      -0.544383\n",
      "       1       0.110923\n",
      "       2      -1.150994\n",
      "b      0       0.375698\n",
      "       1      -0.600639\n",
      "       2      -0.291694\n",
      "c      0      -0.601707\n",
      "       1       1.852278\n",
      "       2      -0.013497\n",
      "d      0      -1.057711\n",
      "       1       0.822545\n",
      "       2      -1.220844\n",
      "dtype: float64\n",
      "--------------------------------------------------\n",
      "size  cloth\n",
      "0     a       -0.544383\n",
      "1     a        0.110923\n",
      "2     a       -1.150994\n",
      "0     b        0.375698\n",
      "1     b       -0.600639\n",
      "2     b       -0.291694\n",
      "0     c       -0.601707\n",
      "1     c        1.852278\n",
      "2     c       -0.013497\n",
      "0     d       -1.057711\n",
      "1     d        0.822545\n",
      "2     d       -1.220844\n",
      "dtype: float64\n"
     ]
    }
   ],
   "source": [
    "index1 = pd.MultiIndex.from_arrays([['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd'],\n",
    "                [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]], names=['cloth', 'size'])\n",
    "\n",
    "ser_obj = pd.Series(np.random.randn(12),index=index1)\n",
    "\n",
    "print(ser_obj)\n",
    "print('-'*50)\n",
    "\n",
    "ser_obj=ser_obj.swaplevel()\n",
    "print(ser_obj)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2024-05-03T05:17:31.435935500Z",
     "start_time": "2024-05-03T05:17:31.392557200Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "# sort_index，指定内层or外层索引排序索引"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "size  cloth\n",
      "0     a        0.241962\n",
      "1     a       -1.913280\n",
      "2     a       -1.724918\n",
      "0     b       -0.562288\n",
      "1     b       -1.012831\n",
      "2     b        0.314247\n",
      "0     c       -0.908024\n",
      "1     c       -1.412304\n",
      "2     c        1.465649\n",
      "0     d       -0.225776\n",
      "1     d        0.067528\n",
      "2     d       -1.424748\n",
      "dtype: float64\n",
      "--------------------------------------------------\n",
      "size  cloth\n",
      "0     a        0.241962\n",
      "      b       -0.562288\n",
      "      c       -0.908024\n",
      "      d       -0.225776\n",
      "1     a       -1.913280\n",
      "      b       -1.012831\n",
      "      c       -1.412304\n",
      "      d        0.067528\n",
      "2     a       -1.724918\n",
      "      b        0.314247\n",
      "      c        1.465649\n",
      "      d       -1.424748\n",
      "dtype: float64\n"
     ]
    }
   ],
   "source": [
    "print(ser_obj)\n",
    "print('-'*50)\n",
    "\n",
    "# sort_index表示按索引排序，但是不改变索引的层级\n",
    "print(ser_obj.sort_index(level=0))  # level=0表示按最外层索引排序"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2024-05-03T05:09:57.490340100Z",
     "start_time": "2024-05-03T05:09:57.424519800Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "size  cloth\n",
      "0     a        0.241962\n",
      "1     a       -1.913280\n",
      "2     a       -1.724918\n",
      "0     b       -0.562288\n",
      "1     b       -1.012831\n",
      "2     b        0.314247\n",
      "0     c       -0.908024\n",
      "1     c       -1.412304\n",
      "2     c        1.465649\n",
      "0     d       -0.225776\n",
      "1     d        0.067528\n",
      "2     d       -1.424748\n",
      "dtype: float64\n"
     ]
    }
   ],
   "source": [
    "print(ser_obj.sort_index(level=1)) # index=1表示按内层索引排序"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-05-03T05:09:57.490340100Z",
     "start_time": "2024-05-03T05:09:57.451445Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### stack、unstack看15"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cloth  size\n",
      "a      0       0.496714\n",
      "       1      -0.138264\n",
      "       2       0.647689\n",
      "b      0       1.523030\n",
      "       1      -0.234153\n",
      "       2      -0.234137\n",
      "c      0       1.579213\n",
      "       1       0.767435\n",
      "       2      -0.469474\n",
      "d      0       0.542560\n",
      "       1      -0.463418\n",
      "       2      -0.465730\n",
      "dtype: float64\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "np.random.seed(42)\n",
    "index1 = pd.MultiIndex.from_arrays([['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd'],\n",
    "                [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]], names=['cloth', 'size'])\n",
    "\n",
    "ser_obj = pd.Series(np.random.randn(12),index=index1)\n",
    "print(ser_obj)\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2024-05-03T06:20:17.192139100Z",
     "start_time": "2024-05-03T06:20:16.835451800Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cloth         a         b         c         d\n",
      "size                                         \n",
      "0      0.496714  1.523030  1.579213  0.542560\n",
      "1     -0.138264 -0.234153  0.767435 -0.463418\n",
      "2      0.647689 -0.234137 -0.469474 -0.465730\n"
     ]
    }
   ],
   "source": [
    "# 把行索引0（最外层索引）变为列索引\n",
    "df_obj=ser_obj.unstack(0)\n",
    "print(df_obj)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-05-03T06:24:29.495449900Z",
     "start_time": "2024-05-03T06:24:29.459989400Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "size          0         1         2\n",
      "cloth                              \n",
      "a      0.496714 -0.138264  0.647689\n",
      "b      1.523030 -0.234153 -0.234137\n",
      "c      1.579213  0.767435 -0.469474\n",
      "d      0.542560 -0.463418 -0.465730\n"
     ]
    }
   ],
   "source": [
    "# 把行索引1变为列索引\n",
    "df_obj=ser_obj.unstack(level=1)\n",
    "print(df_obj)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-05-03T06:24:42.475127200Z",
     "start_time": "2024-05-03T06:24:42.458477200Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cloth  size\n",
      "a      0       0.496714\n",
      "       1      -0.138264\n",
      "       2       0.647689\n",
      "b      0       1.523030\n",
      "       1      -0.234153\n",
      "       2      -0.234137\n",
      "c      0       1.579213\n",
      "       1       0.767435\n",
      "       2      -0.469474\n",
      "d      0       0.542560\n",
      "       1      -0.463418\n",
      "       2      -0.465730\n",
      "dtype: float64\n"
     ]
    }
   ],
   "source": [
    "# 对df进行stack，把列索引放入内层,只能放到内层\n",
    "print(df_obj.stack())"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2024-05-03T06:24:44.953717300Z",
     "start_time": "2024-05-03T06:24:44.935608900Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "# DataFrame的transpose，交换行列索引"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cloth         a         b         c         d\n",
      "size                                         \n",
      "0     -0.544383  0.375698 -0.601707 -1.057711\n",
      "1      0.110923 -0.600639  1.852278  0.822545\n",
      "2     -1.150994 -0.291694 -0.013497 -1.220844\n"
     ]
    }
   ],
   "source": [
    "print(df_obj.transpose())"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-05-03T05:09:57.582095300Z",
     "start_time": "2024-05-03T05:09:57.534224100Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [],
   "metadata": {
    "collapsed": false
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
